<?php
namespace backend\controllers;
use Yii;
use common\extended\system\Util;
use yii\helpers\Url;
use common\models\SysUser;
use common\models\SysMenu;
use common\models\SysRoleMenu;
use common\models\SysLog;
use common\models\SysShop;
/**
 * Base controller
 *
 *
 */
class BaseController extends \yii\web\Controller
{
	/**
	 * 每页显示数据条数
	 * @var int
	 */
	public $pageNavLimit = 15;
	/**
	 * 当前登录用户信息
	 * @var obj
	 */
	private $userInfo;
	/**
	 * 带入sql查询的条件
	 * @var array
	 */
	public $where=[];
	/**
	 * 当前访问controller的名字
	 * @var string
	 */
	private $controllerName;
	/**
	 * 当前访问module的名字
	 * @var string
	 */
	private $moduleName;
	/**
	 * 当前访问method名
	 * @var string
	 */
	private $methodName;
	/**
	 * 菜单ID
	 * @var integer
	 */
	private $menuId;
	/**
	 * request
	 * @var obj
	 */
	protected $request;
	/**
	 * session
	 * @var obj
	 */
	protected $session;
	/**
	 * 设置页面layout
	 * @var unknown
	 */
	public $layout;
	
	/**
	 * 初始化
	 * @date: 2016-1-28 下午2:20:58
	 * @author: futao
	 * @see \yii\base\Object::init()
	 * 备注：加载顺序不能调整
	 */
	public function init()
	{
		parent::init();
		try {
           // var_dump($_SESSION);
			$this->setControllerName();
			$this->setModuleName();
			$this->setMethodName();
			$this->checkLogin();
			$this->bindingParameters();
			$this->checkaccessPermissions();
			$this->setLeftNav();
			$this->operatorLog();
		} catch (\Exception $e){
			echo '初始化错误:'.$e->getMessage().'<br>';
			echo '错误文件:'.$e->getFile().'<br>';
			echo '错误代码:'.$e->getCode().'<br>';
			echo '错误行数:'.$e->getLine();
		}
	}
	/**
	 * 验证是否登录
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function checkLogin()
	{	
		$this->session = \Yii::$app->session; 
		if($this->session->get('userid')=='' || $this->session->get('username')=='' || $this->session->get('userpass')==''){
			//$this->redirect(Url::toRoute('/public/login'));
			echo "<script>";
			echo "location.href='".Url::toRoute('/public/login')."'";
			echo "</script>";
			exit;
		}
		$username = $this->session->get("username");
		$userpass = $this->session->get("userpass");
		$userid = $this->session->get("userid");
		$where[] = "uid = :userid";
		$where[] = "login_name = :login_name";
		$where[] = "password = :password";
		$where[] = "status = ".SysUser::NORMAL;
		$bind[':userid'] = $userid;
		$bind[':login_name'] = $username;
		$bind[':password'] = $userpass;
		$wherestr = implode(" and ",$where);
		$info=SysUser::find()->where($wherestr,$bind)->one();
		if(!$info){
			//$this->redirect(Url::toRoute('/public/login'));
			echo "<script>";
			echo "location.href='".Url::toRoute('/public/login')."'";
			echo "</script>";
			exit;
		}
		
		$this->userInfo = $info;
	} 
	/**
	 * 验证访问权限
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function checkaccessPermissions()
	{
		if($this->controllerName == 'base'){
			return;
		}
		$userinfo = $this->userInfo;
		$where[]="module_name = :modulename";
		$where[]="controller_name = :controllername";
		$where[]="status = ".SysMenu::NORMAL;
		$bind[":controllername"]=$this->controllerName;
		$bind[":modulename"]=$this->moduleName;
		$wherestr = implode(" and ",$where);
		$menuInfo = SysMenu::find()->where($wherestr,$bind)->all();
		if(!$menuInfo){
			$this->error("访问错误！",Url::toRoute('/'));
		}
		$this->menuId = $menuInfo[0]->id;
		foreach ($menuInfo as $k=>$v){
			$info=SysRoleMenu::find()->where("role_id = ".$this->userInfo->user_role." and menu_id = ".$menuInfo[$k]->id)->all();
			if($info){
				break;
			}
		}
		if(!$info){
			$this->error("无权限！",Url::toRoute('/'));
		}
		$this->setCrumbs(SysMenu::find()->where('menu_url = :url',[':url'=>'/'.$this->module->module->requestedRoute])->one()); // 设置面包屑
	}
	/**
	 * 绑定参数
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function bindingParameters()
	{
		$this->request = \Yii::$app->request;
		if($this->userInfo->uid){
			switch ($this->userInfo->user_type){
				case '2' : $this->agentinfo();
					break;
				case '3' : $this->bossinfo();
					break;
				case '4' : $this->shopinfo();
					break;
			}
		}
		
		if($this->moduleName=='business'){
			$this->layout='/agent';
		}else{
			$this->layout='/system';
		}
		$this->getView()->userinfo = $this->userInfo;
		$this->getView()->action = $this->methodName;
		if($this->userInfo->user_type == 3){
			if($this->session->get('shop_id')){
				$this->userInfo->shop_id = $this->session->get('shop_id');
			}
			if($this->userInfo->shop_id){
				$where[] = "shop_id = ".$this->userInfo->shop_id;
				$this->where = $where;
			}
		}elseif($this->userInfo->user_type == 4){
			if($this->userInfo->shop_id){
				$where[] = "shop_id = ".$this->userInfo->shop_id;
				$this->where = $where;
			}
		}
		\Yii::$app->userInfo = $this->userInfo;
	}
	/**
	 * 设置访问控制器名称
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function setControllerName()
	{
		$this->controllerName = $this->id;
        $this->getView()->params['controller_name'] = $this->controllerName;
	}
	/**
	 * 设置访问module名称
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function setModuleName()
	{
		$this->moduleName = $this->module->id;
	}
	/**
	 * 设置访问方法名称
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	private function setMethodName()
	{
		$url = $this->module->module->requestedRoute;
		$urlArr = explode("/",$url);
		$count = count($urlArr)-1;
		if($count<3){
			$this->methodName = $urlArr[$count];
		}
	}
	/**
	 * 操作日志
	 * @date: 2016-1-28 
	 * @author: futao
	 */
	protected function operatorLog()
	{
		$info=[
			'url'=>$this->request->url,
			'bodyParams'=>$this->request->bodyParams
		];
		$logModel = new SysLog();
		$logModel->user_uid = $this->userInfo->uid;
		$logModel->login_name = $this->userInfo->login_name;
		$logModel->ip = $this->request->userIP;
		$logModel->menu_id = $this->menuId;
		$logModel->module_name = $this->methodName;
		$logModel->controller_name = $this->controllerName;
		$logModel->method_name = $this->methodName;
		$logModel->info = json_encode($info);
		$logModel->date_created = date("Y-m-d H:i:s",time());
		$logModel->log_type = $this->userInfo->user_type+1;
		//$logModel->save();
	}
	/**
	 * 赋值代理商所有信息
	 * @date: 2016-1-29 
	 * @author: futao
	 */
	private function agentinfo()
	{
		$this->userInfo=(Object)SysUser::find()
		->select([
			'sys_user.*',
			'sys_agent.*'
		])
		->leftJoin("sys_agent",'sys_agent.agent_uid = sys_user.uid')
		->where("uid = ".$this->userInfo->uid)
		->asArray()
		->one();
	}
	/**
	 * 赋值老板所有信息
	 * @date: 2016-1-29 
	 * @author: futao
	 */
	private function bossinfo()
	{
		$this->userInfo=SysUser::find()
		->select([
			'sys_user.*',
			'sys_boss.*'
		])
		->leftJoin("sys_boss",'boss_uid = uid')
		->where("uid = ".$this->userInfo->uid)
		->asArray()
		->one();
		$shop_info=SysShop::find()->where("boss_uid = ".$this->userInfo['uid']." and status = ".SysShop::NORMAL)->orderby("shop_id asc")->asArray()->one();
		$this->userInfo['shop_id'] = $shop_info['shop_id'];
		$this->userInfo=(object)$this->userInfo;
		$shopList = SysShop::find()
    	->select(['sys_shop.*','sys_user.login_name','sys_user.create_name'])
    	->where("sys_shop.status = ".SysShop::NORMAL." and sys_shop.boss_uid = ".$this->userInfo->uid)
    	->leftJoin('sys_user','shop_uid = uid')->asArray()->all();
		$this->getView()->params['shoplist'] = $shopList;
	}
	/**
	 * 赋值代理商所有信息
	 * @date: 2016-1-29 
	 * @author: futao
	 */
	private function shopinfo(){
		$this->userInfo=(Object)SysUser::find()
		->select([
			'sys_user.*',
			'sys_shop.*'
		])
		->leftJoin("sys_shop",'shop_uid = uid')
		->where("uid = ".$this->userInfo->uid)
		->asArray()
		->one();
	}
	/**
	 * 禁用调试栏
	 * @date: 2016-2-24 
	 * @author: futao
	 */
	public function disableDebugtool()
	{
		$this->session->set('debugState',0);
	}
	/**
	 * 调用工具类方法
	 * @date: 2016-1-28 上午11:29:05
	 * @author: futao
	 * @see \yii\base\Component::__call()
	 */
	public function __call($name, $params)
	{
		$util=new Util();
		return call_user_func_array([$util,$name],$params);
	}
	/**
	 * 错误跳转
	 * @date: 2016-1-28
	 * @author: futao
	 * $message 错误信息
	 * $url 跳转地址
	 * $waitTime 等待时间
	 */
	public function error($message,$url=-1,$waitTime = 3){
		$get = base64_encode("{$message}/{$url}/{$waitTime}");
		echo "<script>";
		echo "location.href='".Url::toRoute(['/error','get'=>$get])."'";
		echo "</script>";
		exit;
	}

	/**
	 * 当前访问的控制器名称
	 * @date: 2016-1-28
	 * @author: futao
	 */
	protected function getcontrollerName()
	{
		return $this->controllerName;
	}
	/**
	 * 获取当前用户信息
	 * @date: 2016-1-28
	 * @author: futao
	 */
	protected function getuserInfo()
	{
		return $this->userInfo;
	}

	/**
	 * 设置左边导航点中菜单
	 * @date: 2016-1-28
	 * @author: futao
	 */
	public function setLeftNav()
	{
		$SysMenu = new SysMenu();
		Yii::$app->view->params['menuList'] = $SysMenu->getAll($this->userInfo->user_role);
	}
	/**
	 * 退出登录
	 * @date: 2016-1-29 
	 * @author: futao
	 */
	public function actionLogout()
    {
        $this->session = \Yii::$app->session;
        $this->session->set('shop_id',null);
		$this->redirect(Url::toRoute('/public/login'));
	}
	/**
	 * 切换分店
	 * @date: 2016-2-23 
	 * @author: futao
	 * @param $shopId
	 */
	public function changeShop($shopId){
		if($this->userInfo->user_type!=3){
			$this->error('当前用户不是老板！');
		}
		$shopList = SysShop::find()
		->select('shop_id')
		->where('boss_uid = :bossId',[':bossId'=>$this->userInfo->uid])
		->asArray()->all();
		$flag = false;
		foreach ($shopList as $v){
			if($v['shop_id']==$shopId){
				$flag = true;
				break;
			}
		}
		if(!$flag){
			return false;
		}
		$this->session->set('shop_id',$shopId);
		return true;
	}
	/**
	 * 设置面包屑
	 * @param array $menuInfo 当前菜单信息array|object
	 */
	public function setCrumbs($menuInfo)
	{
		$crumbs = "<a href=''>首页</a>";
		if ($menuInfo['parent_id'] == 0) { // 顶级
			$crumbs .= "><a href='" . ($menuInfo['menu_url'] ? Url::to([$menuInfo['menu_url']]) : '') . "'>{$menuInfo['titile']}</a>";
		} else {
			$menuInfo2 = SysMenu::findOne($menuInfo['parent_id']);
			if ($menuInfo2['parent_id'] == 0) { // 2级
				$crumbs .= "><a href='" . ($menuInfo2['menu_url'] ? Url::to($menuInfo2['menu_url']) : '') . "'>{$menuInfo2['titile']}</a>><a href='" . ($menuInfo['menu_url'] ? Url::to([$menuInfo['menu_url']]) : '') . "'>{$menuInfo['titile']}</a>";
			} else { // 3级、最高3级
				$menuInfo3 = SysMenu::findOne($menuInfo2['parent_id']);
				$crumbs .= "><a href='" . ($menuInfo3['menu_url'] ? Url::to([$menuInfo3['menu_url']]) : '') . "'>{$menuInfo3['titile']}</a>><a href='" . Url::to([$menuInfo2['menu_url']]) . "'>{$menuInfo2['titile']}</a>><a href='" . ($menuInfo['menu_url'] ? Url::to([$menuInfo['menu_url']]) : '') . "'>{$menuInfo['titile']}</a>";
			}
		}
		Yii::$app->view->params['crumbs'] = $crumbs;
	}
}
